/** 抽离封装好的方法 */
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { showModal, toast } from './utils';
import { removeToken } from './auth';
import { logout, updatePassword } from '../api/manager';
import { useInfoStore } from '../store';


export function useRepassword() {
    const formLabelWidth = '80px';
    const drawerModal = ref(null);
    const formRef = ref(null);
    let form = reactive({
        oldpassword: '',
        password: '',
        repassword: ''
    });
    const newForm = {};
    /** 表单验证规则 */
    const rules = ({
        oldpassword: [
            { required: true, message: '旧密码不能为空', }
        ],
        password: [
            { required: true, message: '新密码不能为空', }
        ],
        repassword: [
            { required: true, message: '确认密码不能为空', }
        ]
    });
    /** 提交修改密码表单 */
    const handleSubmit = async (formEl) => {
        if (!formEl) return
        await formEl.validate((valid) => {
            console.log('打印valid', valid);
            if (valid) {
                console.log('验证通过');
                drawerModal.value.showLoading();
                updatePassword(form).then(res => {
                    console.log(res);
                    drawerModal.value.closeModal();
                    handleClear();
                }).catch(err => {
                    console.log(err);
                    handleClear();
                    toast("修改密码失败", "error");
                }).finally(() => {
                    drawerModal.value.closeLoading();
                })
            } else {
                console.log('验证不通过');
                toast("修改密码失败", "error");
            }
        })
    };
    /** 清空表单 */
    const handleClear = () => {
        const keys = Object.keys(form);
        console.log('打印对象的属性名', keys);
        keys.forEach((item) => {
            // console.log('打印对象的每个属性名', item);
            newForm[item] = ""
        })
        console.log('打印newForm', newForm);
        Object.assign(form, newForm);
    };
    return {
        drawerModal,
        formRef,
        form,
        rules,
        formLabelWidth,
        handleSubmit,
        handleClear,
    }
}

/** 封装退出登录方法 */
export function useLogout() {
    const router = useRouter();
    const userStore = useInfoStore();
    /** 退出登录弹出框 */
    const handleLogout = () => {
        showModal('退出登录', '是否退出当前账号？', 'warning').then(res => {
            logout().then(() => {
                // 1、移除token
                removeToken();
                // 2、清除pinia中的个人信息数据
                userStore.userInfo = {};
                // 3、页面跳转
                router.push('/login');
                // 4、弹出提示框
                toast('退出登录成功', 'success');
            }).catch(() => {
                toast('退出登录失败', 'error');
            })

        }).catch(err => {
            console.log('点击了取消');
        })

    }
    return {
        handleLogout
    }
}